package pure.csw.activemq.schedualingdeliver;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ScheduledMessage;
import pure.csw.common.Constant;

import javax.jms.*;
import java.io.IOException;

public class Produce {
    public static void main(String[] args) throws JMSException, InterruptedException, IOException {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(Constant.URL);
        Connection connection = factory.createConnection();
        connection.start();
        //开启一次会话，非事务，自动确认
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //消息以队列的方式存储
        Queue queue = session.createQueue(Constant.QUEUENAME);
        //创建文本消息
        TextMessage message = session.createTextMessage();
        message.setText("the message");
        long delay = 30 * 1000;
        long period = 30 * 1000;
        int repeat = 9;
        //指定消息在30s内发送，且每30s发送10条消息
        message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY,delay);
        message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD,period);
        message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT,repeat);
        //cron 每个星期5早上5点发送一次消息
        message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON,"0 5 * * 5");

        //创建消息的生产者
        MessageProducer producer = session.createProducer(queue);
        //创建消息的消费者
        MessageConsumer consumer = session.createConsumer(queue);
        System.out.println("produce send message start");
        //发送消息，持久，优先级为4，存活时间为5秒
        producer.send(message,DeliveryMode.PERSISTENT,4,5000);
        //消费以监听的方式获取消息
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println("consumer:"+textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        //等待消息的发送和监听完成
        Thread.sleep(5000);
        //关闭资源
        producer.close();
        consumer.close();
        session.close();
        connection.close();
    }
}
